package com.hd123.rumba.gwt.widget2e.client.dialog;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.hd123.rumba.gwt.base.client.BWithUCN;

/**
 * 简化的浏览对话框：
 * <p>
 * <li>表格只显示代码名称两列。
 * <li>筛选界面只有代码名称两项。
 * <li>远程调用获得对象类型为BWithUCN。
 * <li>onSelected获得对象类型为BWithUCN。
 * 
 * @author LiQi
 * 
 */
public abstract class RSimpleBrowserDialog extends RBrowserDialog {

  /** 表格列标题 */
  public static final String COLUMN_CAPTION_CODE = "代码";
  public static final String COLUMN_CAPTION_NAME = "名称";
  public static final String[] COLUMN_CAPTIONS = new String[] {
      COLUMN_CAPTION_CODE, COLUMN_CAPTION_NAME };

  /** 筛选回调 */
  private RCodeNameFilterCallbackImpl filterCallback;

  public RSimpleBrowserDialog() {
    super(COLUMN_CAPTIONS);
    setBrowserCallback(new BrowserCallback());

    filterCallback = new RCodeNameFilterCallbackImpl();
    setFilterCallback(filterCallback);
    setFilterStyle(FILTER_STYLE_PANEL);
  }

  /**
   * 执行RPC调用获得浏览窗口展示用的数据集，，数据集应为RPageData类型，其元素应为BWithUCN
   * 
   * @param filter
   *          筛选对象，包含当前页序号、每页记录数、筛选数据、排序数据
   * @param callback
   *          实现类应把callback作为RPC调用的回调
   */
  public abstract void fetchData(CodeNameFilter filter, AsyncCallback callback);

  /**
   * 用户选择一行后触发
   * 
   * @param object
   *          选中行对应的对象
   */
  public abstract void onSelected(BWithUCN object);

  /**
   * 浏览对话框回调
   * 
   * @author LiQi
   * 
   */
  private class BrowserCallback implements RBrowserCallback {

    public void fetchData(int page, int pageSize, String sortField, String sortDir,
        AsyncCallback callback) {
      CodeNameFilter filter = filterCallback.getFilter();
      filter.setPage(page);
      filter.setPageSize(pageSize);
      filter.clearOrders();
      filter.setSort(sortField);
      filter.setDirection(sortDir);
      RSimpleBrowserDialog.this.fetchData(filter, callback);
    }

    public String displayData(Object data, int col) {
      if (!(data instanceof BWithUCN))
        throw new RuntimeException("fetch获得的数据集的元素应为BWithUCN类型");

      BWithUCN ucn = (BWithUCN) data;
      switch (col) {
      case 0:
        return ucn.getCode();
      case 1:
        return ucn.getName();
      default:
        return "";
      }
    }

    public void onSelected(Object object) {
      if (!(object instanceof BWithUCN))
        throw new RuntimeException("fetch获得的数据集的元素应为BWithUCN类型");

      RSimpleBrowserDialog.this.onSelected((BWithUCN) object);
    }

  }
}
